package gradle.common.core.context;

import org.springframework.beans.BeansException;
import org.springframework.context.*;
import org.springframework.core.env.Environment;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

@Component
public class SpringApplicationContext implements ApplicationContextAware {

    private static ApplicationContext APPLICATION_CONTEXT = null;

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        APPLICATION_CONTEXT = applicationContext;
    }

    public static <T> T getBean(Class<T> tClass) {
        return APPLICATION_CONTEXT.getBean(tClass);
    }

    public static <T> T getBeanIfNull(Class<T> tClass) {
        try {
            return APPLICATION_CONTEXT.getBean(tClass);
        } catch (BeansException e) {
            return null;
        }
    }


    public static <T> T getBean(String name, Class<T> tClass) {
        return APPLICATION_CONTEXT.getBean(name, tClass);
    }

    public static Object getBean(String name) {
        return APPLICATION_CONTEXT.getBean(name);
    }

    public static String getProperty(String key) {
        return APPLICATION_CONTEXT.getBean(Environment.class).getProperty(key);
    }

}
